import { ElMessage } from "element-plus";
import Nifi from "../../nifi";
import { h, reactive, ref } from "vue";
import AddEl from "./add.vue"
//
import TabsElem from "./tabs.vue"
import { t } from "../../i18n/index"

export default (nifi: Nifi) => {

    // const D = reactive({id:'',name:''})
    // nifi.graph.onMounted(() => {
    //     D.id = nifi.group.component?.parameterContext?.id;
    //     D.name = nifi.group.component?.parameterContext.component.name
    // })
    // 当前处理组的 参数集合
    const enabled = ref(true);
    const data = new Map<string, any>()
    const refreshList = async () => {
        get();
    }

    const get = async (id = nifi.group.component?.parameterContext?.id, isForce = false) => {
        if (id == undefined) {
            if (enabled.value == true) {
                ElMessage.warning(t('param-index-get-warn'));
            }
            enabled.value = false;
            return undefined
        }
        enabled.value = true;
        //
        if (!isForce && data.has(id)) { return data.get(id) }
        const url = `/nifi-api/parameter-contexts/${id}?includeInheritedParameters=true`;
        try {
            const res = await nifi.api.get(url);
            data.set(id, res)
            return res;
        } catch (error) {
            ElMessage.error(t('param-index-get-failed', { error }))
            console.error(error);
            return false;
        }
    }

    //
    const update = async (id = nifi.group.component?.parameterContext?.id, d: any) => {
        // /nifi-api/parameter-contexts/e02ec4f8-0192-1000-9a09-dfb7e6486eec/update-requests
        let url = `/nifi-api/parameter-contexts/${id}/update-requests`
        let res: any;
        try {
            // 修改请求
            res = await nifi.api.post(url, d)
            //
            url = `/nifi-api/parameter-contexts/${id}/update-requests/${res.request.requestId}`
            //
            while (!res.request.complete) {
                res = await nifi.api.get(url);
            }
            //
            url = url + '?disconnectedNodeAcknowledged=false';
            res = await nifi.api.delete(url);
            //
        } catch (error) {
            ElMessage.error(t('param-index-update-failed', { error }))
            console.error(error);
            return false;
        }
    }

    const addContext = async (d: any) => {
        const data = {
            "revision": {
                "version": 0,
                "clientId": nifi.flow.clientId
            },
            "disconnectedNodeAcknowledged": false,
            "component": {
                "parameters": [],
                "inheritedParameterContexts": [],
                ...d,
            }
        }

        const url = '/nifi-api/parameter-contexts';
        try {
            const res = await nifi.api.post(url,data);
            return res;
        } catch (error) {
            console.error(error)
        }

    }
    //
    const getParameters = (d: any) => {
        const names = getSelfParameterNames(d);
        return d?.component?.parameters?.filter((t: any) => t.parameter.parameterContext.id == d.id || !names.includes(t.parameter.name)).map((t: any) => ({ ...t.parameter, sort: t.parameter.parameterContext.id == d.id ? 1 : 2 })).sort((a: any, b: any) => a.sort - b.sort) || []
    }

    const getSelfParameters = (d: any) => { return d?.component?.parameters?.filter((t: any) => t.parameter.parameterContext.id == d.id).map((t: any) => ({ ...t.parameter })) }
    const getSelfParameterNames = (d: any) => { return d?.component?.parameters?.filter((t: any) => t.parameter.parameterContext.id == d.id).map((t: any) => t.parameter.name) }

    const getCurrentParameters = async () => {
        const res = await get();
        if (res) {
            return getParameters(res)
        }
        return []
    }


    // 打开 参数管理的弹框
    const open = (search?: string) => {
        nifi.box.dialog((box) => h(TabsElem, { nifi, box, search }), { showFooter: false })
    }

    // 新增参数上下文

    // 将值转换成参数
    const trans = async (name: string, value = "") => {
        const id = nifi.group.component?.parameterContext?.id;
        const cd = await get(id, true)
        if (!id || !cd) return undefined;
        const names = getSelfParameterNames(cd)
        const row = { name, value, description: "", sensitive: false }
        return new Promise((resolve) => {
            nifi.box.dialog((box) => h(AddEl, {
                title: t('param-index-trans-title'), names, box, row, onSubmit: async ({ description, value, name }) => {
                    row.name = name;
                    row.value = value;
                    row.description = description;
                    //
                    const component = { ...cd.component, parameters: [{ parameter: row }] }
                    const data = { ...cd, component }
                    const bool = await update(id, data)
                    if (bool != false) {
                        resolve(name)
                    }
                    else {
                        resolve(false)
                    }
                }
            }))
        })

    }



    return {
        enabled,
        //
        get,
        update,
        addContext,
        //
        refreshList,
        //
        getParameters,
        getSelfParameters,
        getSelfParameterNames,
        getCurrentParameters,
        open,
        trans
    }

}